'use strict'

var Code = {}

Code.workspace = null

Code.getStringParamFromUrl = function (name, defaultValue) {
  var val = location.search.match(new RegExp('[?&]' + name + '=([^&]+)'))
  return val ? decodeURIComponent(val[1].replace(/\+/g, '%20')) : defaultValue
}

Code.loadBlocks = function (defaultXml) {
  if (defaultXml) {
    console.log(defaultXml)
    Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom(defaultXml), Code.workspace)
  }
}

Code.changeCodingLanguage = function() {
  var codeMenu = document.getElementById('code_menu');
  Code.tabClick(codeMenu.options[codeMenu.selectedIndex].value);
}

Code.bindClick = function (el, func) {
  if (typeof el == 'string') {
    el = document.getElementById(el)
  }
  el.addEventListener('click', func, true)
  el.addEventListener('touchend', func, true)
}

Code.importPrettify = function () {
  var script = document.createElement('script')
  script.setAttribute('src', 'https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js')
  document.head.appendChild(script)
}

/**
 * Compute the absolute coordinates and dimensions of an HTML element.
 * @param {!Element} element Element to match.
 * @return {!Object} Contains height, width, x, and y properties.
 * @private
 */
Code.getBBox_ = function (element) {
  var height = element.offsetHeight
  var width = element.offsetWidth
  var x = 0
  var y = 0
  do {
    x += element.offsetLeft
    y += element.offsetTop
    element = element.offsetParent
  } while (element)
  return {
    height: height,
    width: width,
    x: x,
    y: y
  }
}

Code.LANG = 'zh-hans'
Code.TABS_ = ['blocks', 'javascript', 'xml']
Code.TABS_DISPLAY_ = [
  'Blocks', 'JavaScript', 'XML',
]
Code.selected = 'blocks'


Code.tabClick = function (clickedName) {
  // If the XML tab was open, save and render the content.
  if (document.getElementById('tab_xml').classList.contains('tabon')) {
    var xmlTextarea = document.getElementById('content_xml')
    var xmlText = xmlTextarea.value
    var xmlDom = null
    try {
      xmlDom = Blockly.Xml.textToDom(xmlText)
    } catch (e) {
      var q =
        window.confirm(MSG['badXml'].replace('%1', e))
      if (!q) {
        // Leave the user on the XML tab.
        return
      }
    }
    if (xmlDom) {
      Code.workspace.clear()
      Blockly.Xml.domToWorkspace(xmlDom, Code.workspace)
    }
  }

  if (document.getElementById('tab_blocks').classList.contains('tabon')) {
    Code.workspace.setVisible(false)
  }
  // Deselect all tabs and hide all panes.
  for (var i = 0; i < Code.TABS_.length; i++) {
    var name = Code.TABS_[i]
    var tab = document.getElementById('tab_' + name)
    tab.classList.add('taboff')
    tab.classList.remove('tabon')
    document.getElementById('content_' + name).style.visibility = 'hidden'
  }

  // Select the active tab.
  Code.selected = clickedName
  var selectedTab = document.getElementById('tab_' + clickedName)
  selectedTab.classList.remove('taboff')
  selectedTab.classList.add('tabon')
  // Show the selected pane.
  document.getElementById('content_' + clickedName).style.visibility =
    'visible'
  Code.renderContent()
  // The code menu tab is on if the blocks tab is off.
  var codeMenuTab = document.getElementById('tab_code')
  if (clickedName == 'blocks') {
    Code.workspace.setVisible(true)
    codeMenuTab.className = 'taboff'
  } else {
    codeMenuTab.className = 'tabon'
  }
  // Sync the menu's value with the clicked tab value if needed.
  var codeMenu = document.getElementById('code_menu')
  for (var i = 0; i < codeMenu.options.length; i++) {
    if (codeMenu.options[i].value == clickedName) {
      codeMenu.selectedIndex = i
      break
    }
  }
  Blockly.svgResize(Code.workspace)
}

/**
 * Populate the currently selected pane with content generated from the blocks.
 */
Code.renderContent = function () {
  var content = document.getElementById('content_' + Code.selected)
  // Initialize the pane.
  if (content.id == 'content_xml') {
    var xmlTextarea = document.getElementById('content_xml')
    var xmlDom = Blockly.Xml.workspaceToDom(Code.workspace)
    var xmlText = Blockly.Xml.domToPrettyText(xmlDom)
    xmlTextarea.value = xmlText
    xmlTextarea.focus()
  } else if (content.id == 'content_javascript') {
    Code.attemptCodeGeneration(Blockly.JavaScript)
  }
  if (typeof PR == 'object') {
    PR.prettyPrint()
  }
}

/**
 * Attempt to generate the code and display it in the UI, pretty printed.
 * @param generator {!Blockly.Generator} The generator to use.
 */
Code.attemptCodeGeneration = function (generator) {
  var content = document.getElementById('content_' + Code.selected)
  content.textContent = ''
  if (Code.checkAllGeneratorFunctionsDefined(generator)) {
    var code = generator.workspaceToCode(Code.workspace)
    content.textContent = code
    // Remove the 'prettyprinted' class, so that Prettify will recalculate.
    content.className = content.className.replace('prettyprinted', '')
  }
}

/**
 * Check whether all blocks in use have generator functions.
 * @param generator {!Blockly.Generator} The generator to use.
 */
Code.checkAllGeneratorFunctionsDefined = function (generator) {
  var blocks = Code.workspace.getAllBlocks(false)
  var missingBlockGenerators = []
  for (var i = 0; i < blocks.length; i++) {
    var blockType = blocks[i].type
    if (!generator[blockType]) {
      if (missingBlockGenerators.indexOf(blockType) == -1) {
        missingBlockGenerators.push(blockType)
      }
    }
  }

  var valid = missingBlockGenerators.length == 0
  if (!valid) {
    var msg = 'The generator code for the following blocks not specified for ' +
      generator.name_ + ':\n - ' + missingBlockGenerators.join('\n - ')
    Blockly.alert(msg)  // Assuming synchronous. No callback.
  }
  return valid
}

/**
 * Initialize Blockly.  Called on page load.
 */
Code.init = function () {
  Code.initLanguage()

  var container = document.getElementById('content_area')
  var onresize = function (e) {
    var bBox = Code.getBBox_(container)
    for (var i = 0; i < Code.TABS_.length; i++) {
      var el = document.getElementById('content_' + Code.TABS_[i])
      el.style.top = bBox.y + 'px'
      el.style.left = bBox.x + 'px'
      // Height and width need to be set, read back, then set again to
      // compensate for scrollbars.
      el.style.height = bBox.height + 'px'
      el.style.height = (2 * bBox.height - el.offsetHeight) + 'px'
      el.style.width = bBox.width + 'px'
      el.style.width = (2 * bBox.width - el.offsetWidth) + 'px'
    }
    // Make the 'Blocks' tab line up with the toolbox.
    if (Code.workspace && Code.workspace.getToolbox().width) {
      document.getElementById('tab_blocks').style.minWidth =
        (Code.workspace.getToolbox().width - 38) + 'px'
      // Account for the 19 pixel margin and on each side.
    }
  }
  window.addEventListener('resize', onresize, false)

  // The toolbox XML specifies each category name using Blockly's messaging
  // format (eg. `<category name="%{BKY_CATLOGIC}">`).
  // These message keys need to be defined in `Blockly.Msg` in order to
  // be decoded by the library. Therefore, we'll use the `MSG` dictionary that's
  // been defined for each language to import each category name message
  // into `Blockly.Msg`.
  // TODO: Clean up the message files so this is done explicitly instead of
  // through this for-loop.
  for (var messageKey in MSG) {
    if (messageKey.indexOf('cat') == 0) {
      Blockly.Msg[messageKey.toUpperCase()] = MSG[messageKey]
    }
  }

  var toolboxText = TOOLBOX
  var toolboxXml = Blockly.Xml.textToDom(toolboxText)

  Code.workspace = Blockly.inject('content_blocks',
    {
      grid:
        {
          spacing: 25,
          length: 3,
          colour: '#ccc',
          snap: true
        },
      media: '../../media/',
      toolbox: toolboxXml,
      zoom:
        {
          controls: true,
          wheel: true
        }
    })

  // Add to reserved word list: Local variables in execution environment (runJS)
  // and the infinite loop detection function.
  Blockly.JavaScript.addReservedWords('code,timeouts,checkTimeout')

  Code.loadBlocks('')
  Code.tabClick(Code.selected)

  Code.bindClick('trashButton',
    function () {
      Code.discard()
      Code.renderContent()
    })
  Code.bindClick('runButton', Code.runJS)

  for (var i = 0; i < Code.TABS_.length; i++) {
    var name = Code.TABS_[i]
    Code.bindClick('tab_' + name,
      function (name_) {
        return function () {
          Code.tabClick(name_)
        }
      }(name))
  }
  Code.bindClick('tab_code', function (e) {
    if (e.target !== document.getElementById('tab_code')) {
      // Prevent clicks on child codeMenu from triggering a tab click.
      return
    }
    Code.changeCodingLanguage()
  })

  onresize()
  Blockly.svgResize(Code.workspace)

  // Lazy-load the syntax-highlighting.
  window.setTimeout(Code.importPrettify, 1)
}

/**
 * Initialize the page language.
 */
Code.initLanguage = function () {
  // Populate the coding language selection menu.
  var codeMenu = document.getElementById('code_menu')
  codeMenu.options.length = 0
  for (var i = 1; i < Code.TABS_.length; i++) {
    codeMenu.options.add(new Option(Code.TABS_DISPLAY_[i], Code.TABS_[i]))
  }
  codeMenu.addEventListener('change', Code.changeCodingLanguage)

  // Inject language strings.
  document.title += ' ' + MSG['title']
  document.getElementById('tab_blocks').textContent = MSG['blocks']
  document.getElementById('runButton').title = MSG['runTooltip']
  document.getElementById('trashButton').title = MSG['trashTooltip']
}

Code.runJS = function () {
  Blockly.JavaScript.INFINITE_LOOP_TRAP = 'checkTimeout();\n'
  var timeouts = 0
  var checkTimeout = function () {
    if (timeouts++ > 1000000) {
      throw MSG['timeout']
    }
  }
  var code = Blockly.JavaScript.workspaceToCode(Code.workspace)
  Blockly.JavaScript.INFINITE_LOOP_TRAP = null
  try {
    eval(code)
  } catch (e) {
    alert(MSG['badCode'].replace('%1', e))
  }
}

/**
 * Discard all blocks from the workspace.
 */
Code.discard = function () {
  var count = Code.workspace.getAllBlocks(false).length
  if (count < 2 ||
    window.confirm(Blockly.Msg['DELETE_ALL_BLOCKS'].replace('%1', count))) {
    Code.workspace.clear()
  }
}

window.addEventListener('load', Code.init)
